package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private QuanZiApi quanZiApi;
    @Override
    public String saveVideo(Video video) {
        if (!ObjectUtil.isAllNotEmpty(video.getPicUrl(),video.getUserId(),video.getVideoUrl())) {
            return null;
        }
        video.setId(ObjectId.get());
        video.setVid(this.idService.createId(IdType.VIDEO));
        //发布时间
        video.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo=new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        String redisKey="QUANZI_VIDEO_RECOMMEND_"+userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<Long> vids=new ArrayList<>();
        int total=0;
        if (StrUtil.isNotEmpty(redisData)) {
            String[] split = StrUtil.split(redisData, ",");
            int[] ints = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex=ints[0];
            int endIndex=ints[1];
            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Long.valueOf(split[i]));
            }
            total=split.length;
        }
        if(CollUtil.isEmpty(vids)){
            int i = PageUtil.totalPage(total, pageSize);
            Pageable pageable=PageRequest.of(page-i-1,pageSize,Sort.by(Sort.Order.desc("created")));;
            Query query=new Query().with(pageable);
            List<Video> videos = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videos);
            return pageInfo;
        }
        Query query=Query.query(Criteria.where("vid").in(vids));
        List<Video> videos = this.mongoTemplate.find(query, Video.class);
        if (CollUtil.isEmpty(videos)) {
            return pageInfo;
        }
        pageInfo.setRecords(videos);

        return pageInfo;
    }

    @Override
    public Video queryVideoById(String publishId) {
        return this.mongoTemplate.findById(new ObjectId(publishId), Video.class);
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            if (this.isFollowUser(userId,followUserId)) {
                return false;
            }
            FollowUser followUser=new FollowUser();
            followUser.setCreated(System.currentTimeMillis());
            followUser.setFollowUserId(followUserId);
            followUser.setUserId(userId);
            followUser.setId(ObjectId.get());
            this.mongoTemplate.save(followUser);
            // 放入redis
            String redisKey=this.getFollowUserPrefix(userId);
            String hashKey=String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey,hashKey,"1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private String getFollowUserPrefix(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX+userId;
    }

    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        try {
            if (!this.isFollowUser(userId,followUserId)) {
                return false;
            }

            Query query=Query.query(Criteria.where("userId").is(userId)
                    .and("followUserId").is(followUserId));
            DeleteResult remove = this.mongoTemplate.remove(query, FollowUser.class);
            if (remove.getDeletedCount()>0) {
                //删除数据库的同时删除redis
                String redisKey=this.getFollowUserPrefix(userId);
                String hashKey=String.valueOf(followUserId);
                this.redisTemplate.opsForHash().delete(redisKey,hashKey);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey=this.getFollowUserPrefix(userId);
        String hashKey=String.valueOf(followUserId);
        Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(o)) {
            if(StrUtil.equals(o.toString(),"1")){
                return true;
            }
        }
        //此处无此表,一般不会出现库有redis无的情况
        // 考虑到redis的删除策略,可能淘汰到对应redisKey,此时数据库就会出现重复数据
        try {
            Query query=Query.query(Criteria.where("userId").is(userId)
            .and("followUserId").is(followUserId));
            FollowUser one = this.mongoTemplate.findOne(query, FollowUser.class);
            if (ObjectUtil.isNotEmpty(one)) {
    //            放入redis方便下次命中,缓冲加快速度
                this.redisTemplate.opsForHash().put(redisKey,followUserId,"1");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
